package com.net.tkc.pro.controller;

import com.net.tkc.pro.entity.Collect;
import com.net.tkc.pro.entity.History;
import com.net.tkc.pro.entity.Post;
import com.net.tkc.pro.entity.ResultEntity;
import com.net.tkc.pro.impl.HistoryImpl;
import com.net.tkc.pro.tool.JsonUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin //解决跨域问题
@RestController
@RequestMapping("/History/")
public class HistoryController {
    ResultEntity resultEntity = null;
    @Resource
    HistoryImpl historyImpl;

    /**
     * 根据用户id查找查看帖子
     * @param userid 用户id
     * @return
     */
    @GetMapping("GetList")
    private String getList(
            @RequestParam("userid") int userid
    ){
        resultEntity = new ResultEntity();
        try{
            List<History> list =historyImpl.getList(userid);
            if (list.size()!=0){
                resultEntity.setCount(list.size());
                resultEntity.setCode("0");
                resultEntity.setData(list);
                resultEntity.setMsg("获取成功！");
            }else{
                resultEntity.setMsg("获取失败,请查看是否有数据");
                resultEntity.setCode("2");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setMsg("获取失败");
            resultEntity.setCode("1");
        }
        return JsonUtil.getJsonTool().toJson(resultEntity);
    }

    /**
     * 添加浏览记录
     * @param postid 帖子id
     * @param userid 用户id
     * @return
     */
    @PostMapping("History")
    private String addHistory(
            @RequestParam("postid") int postid,
            @RequestParam("userid") int userid
    ){
        resultEntity = new ResultEntity();
        History history=new History();
        history.setPostid(postid);
        history.setUserid(userid);
        DateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date=new Date();
        String Time=dateFormat.format(date);
        history.setTime(Time);
        try{
            int result = historyImpl.addHistory(history);
            if(result>0){
                resultEntity.setCode("0");
                resultEntity.setMsg("添加成功！");
            }else{
                resultEntity.setCode("1");
                resultEntity.setMsg("添加失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg(e.getMessage());
        }
        return JsonUtil.getJsonTool().toJson(resultEntity);
    }
}
